$(document).ready(function() {
    // 初始化页面
    loadUserInfo();
    loadTradeHistory();

    // 菜单切换功能
    $('.menu-btn').click(function() {
        const target = $(this).data('target');

        // 更新菜单激活状态
        $('.menu-btn').removeClass('active');
        $(this).addClass('active');

        // 显示对应内容区域
        $('.content-section').removeClass('active');
        $(`#${target}`).addClass('active');

        // 特殊页面加载数据
        if (target === 'history') {
            loadTradeHistory();
        } else if (target === 'loss') {
            loadLossInfo();
        } else if (target === 'home') {
            loadHomeInfo();
        }
    });

    // 快捷操作按钮
    $('.action-btn').click(function() {
        const target = $(this).data('target');

        // 更新菜单激活状态
        $('.menu-btn').removeClass('active');
        $(`.menu-btn[data-target="${target}"]`).addClass('active');

        // 显示对应内容区域
        $('.content-section').removeClass('active');
        $(`#${target}`).addClass('active');
    });

    // 存款操作
    $('#depositSubmit').click(function() {
        const amount = parseFloat($('#depositAmount').val());
        const remark = $('#depositRemark').val() || '存款';

        if (!amount || amount <= 0) {
            showError('请输入有效的存款金额');
            return;
        }

        $.post("{{ url_for('client.deposit') }}", {
            amount: amount,
            remark: remark
        }, function(response) {
            if (response.success) {
                showSuccess('存款成功！');
                updateBalance(response.new_balance);
                $('#depositAmount').val('');
                $('#depositRemark').val('');
            } else {
                showError(response.error || '存款失败');
            }
        }).fail(function(xhr) {
            showError(xhr.responseJSON?.error || '服务器错误');
        });
    });

    // 取款操作
    $('#withdrawSubmit').click(function() {
        const amount = parseFloat($('#withdrawAmount').val());
        const remark = $('#withdrawRemark').val() || '取款';

        if (!amount || amount <= 0) {
            showError('请输入有效的取款金额');
            return;
        }

        $.post("{{ url_for('client.withdraw') }}", {
            amount: amount,
            remark: remark
        }, function(response) {
            if (response.success) {
                showSuccess('取款成功！');
                updateBalance(response.new_balance);
                $('#withdrawAmount').val('');
                $('#withdrawRemark').val('');
            } else {
                showError(response.error || '取款失败');
            }
        }).fail(function(xhr) {
            showError(xhr.responseJSON?.error || '服务器错误');
        });
    });

    // 转账操作
    $('#transferSubmit').click(function() {
        const toCardId = $('#toCardId').val().trim();
        const amount = parseFloat($('#transferAmount').val());
        const remark = $('#transferRemark').val() || '转账';

        if (!toCardId) {
            showError('请输入目标银行卡号');
            return;
        }

        if (!amount || amount <= 0) {
            showError('请输入有效的转账金额');
            return;
        }

        $.post("{{ url_for('client.transfer') }}", {
            to_card_id: toCardId,
            amount: amount,
            remark: remark
        }, function(response) {
            if (response.success) {
                showSuccess('转账成功！');
                updateBalance(response.new_balance);
                $('#toCardId').val('');
                $('#transferAmount').val('');
                $('#transferRemark').val('');
            } else {
                showError(response.error || '转账失败');
            }
        }).fail(function(xhr) {
            showError(xhr.responseJSON?.error || '服务器错误');
        });
    });

    // 挂失操作
    $('#reportLossBtn').click(function() {
        if (!confirm('确定要挂失此银行卡吗？挂失后将无法进行任何交易！')) {
            return;
        }

        $.post("{{ url_for('client.report_loss') }}", function(response) {
            if (response.success) {
                showSuccess('银行卡已成功挂失！');
                loadLossInfo();
            } else {
                showError(response.error || '挂失失败');
            }
        }).fail(function(xhr) {
            showError(xhr.responseJSON?.error || '服务器错误');
        });
    });

    // 修改密码
    $('#changePasswordBtn').click(function() {
        const oldPassword = $('#oldPassword').val().trim();
        const newPassword = $('#newPassword').val().trim();
        const confirmPassword = $('#confirmPassword').val().trim();

        if (!oldPassword) {
            showError('请输入原密码');
            return;
        }

        if (!newPassword || newPassword.length !== 6) {
            showError('新密码必须为6位数字');
            return;
        }

        if (newPassword !== confirmPassword) {
            showError('两次输入的新密码不一致');
            return;
        }

        $.post("{{ url_for('client.change_password') }}", {
            old_password: oldPassword,
            new_password: newPassword
        }, function(response) {
            if (response.success) {
                showSuccess('密码修改成功！');
                $('#oldPassword').val('');
                $('#newPassword').val('');
                $('#confirmPassword').val('');
            } else {
                showError(response.error || '密码修改失败');
            }
        }).fail(function(xhr) {
            showError(xhr.responseJSON?.error || '服务器错误');
        });
    });

    // 刷新交易记录
    $('#refreshHistory').click(function() {
        loadTradeHistory();
    });

    // 导出交易记录
    $('#exportBtn, #exportHistoryBtn').click(function() {
        window.location.href = "{{ url_for('client.export_trade_history') }}";
    });

    // 加载用户信息
    function loadUserInfo() {
        $.get("{{ url_for('client.get_balance') }}", function(response) {
            if (response.error) {
                showError(response.error);
                return;
            }

            $('#cardIdDisplay').text(`卡号: ${response.cardID}`);
            $('#balanceDisplay').text(`余额: ¥${response.balance.toFixed(2)}`);
            $('#welcomeCardId').text(response.cardID);
            $('#welcomeBalance').text(`¥${response.balance.toFixed(2)}`);
            $('#historyBalance').text(`¥${response.balance.toFixed(2)}`);
        }).fail(function() {
            showError('无法加载账户信息');
        });
    }

    // 加载挂失信息
    function loadLossInfo() {
        $.get("{{ url_for('client.get_balance') }}", function(response) {
            if (response.error) {
                showError(response.error);
                return;
            }

            $('#lossCardId').text(response.cardID);

            $.get("{{ url_for('client.get_trade_history') }}", function(history) {
                if (history.length > 0) {
                    const lastTrade = history[0];
                    const tradeTypeMap = {
                        '存款': '收入',
                        '取款': '支出',
                        '转账': lastTrade.remark.includes('转入') ? '收入' : '支出'
                    };

                    $('#lastTrade').html(`
                        ${lastTrade.tradeDate} 
                        <span class="${tradeTypeMap[lastTrade.tradeType] === '收入' ? 'text-success' : 'text-danger'}">
                            ${tradeTypeMap[lastTrade.tradeType]} ¥${lastTrade.tradeMoney.toFixed(2)}
                        </span>
                    `);
                }
            });
        }).fail(function() {
            showError('无法加载账户信息');
        });

        // 获取卡状态
        const cardId = "{{ session.get('cardID') }}";
        if (cardId) {
            $.get(`/api/card/${cardId}`, function(card) {
                if (card) {
                    const status = card.IsReportLoss === '是' ?
                        `<span class="text-danger">已挂失</span>` :
                        `<span class="text-success">正常</span>`;

                    $('#accountStatus').html(status);
                    $('#lossStatus').html(status);
                }
            });
        }
    }

    // 加载首页信息
    function loadHomeInfo() {
        loadUserInfo();
        loadLossInfo();
    }

    // 加载交易记录
    function loadTradeHistory() {
        $.get("{{ url_for('client.get_trade_history') }}", function(history) {
            const tbody = $('#tradeHistoryBody');
            tbody.empty();

            if (history.error) {
                showError(history.error);
                return;
            }

            if (history.length === 0) {
                tbody.append('<tr><td colspan="4" class="text-center">暂无交易记录</td></tr>');
                return;
            }

            history.forEach(trade => {
                const tradeTypeClass = trade.tradeType === '存款' ||
                    (trade.tradeType === '转账' && trade.remark.includes('转入')) ?
                    'text-success' : 'text-danger';

                const tradeSign = trade.tradeType === '存款' ||
                    (trade.tradeType === '转账' && trade.remark.includes('转入')) ?
                    '+' : '-';

                tbody.append(`
                    <tr>
                        <td>${trade.tradeDate}</td>
                        <td>${trade.tradeType}</td>
                        <td class="${tradeTypeClass}">${tradeSign}¥${trade.tradeMoney.toFixed(2)}</td>
                        <td>${trade.remark}</td>
                    </tr>
                `);
            });
        }).fail(function() {
            showError('无法加载交易记录');
        });
    }

    // 更新余额显示
    function updateBalance(newBalance) {
        $('.balance, #balanceDisplay, #welcomeBalance, #historyBalance').text(`¥${newBalance.toFixed(2)}`);
    }

    // 显示成功消息
    function showSuccess(message) {
        $('#errorMessages').html(`
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> ${message}
            </div>
        `);

        // 3秒后自动消失
        setTimeout(() => {
            $('#errorMessages').empty();
        }, 3000);
    }

    // 显示错误消息
    function showError(message) {
        $('#errorMessages').html(`
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i> ${message}
            </div>
        `);

        // 5秒后自动消失
        setTimeout(() => {
            $('#errorMessages').empty();
        }, 5000);
    }

    // 每30秒更新一次余额
    setInterval(loadUserInfo, 30000);
});